// pages/coupon/index.js
import api from '../../api/index'
import { AppId } from '../../api/config'
import { userInfoStore } from '../../store/userInfo'
var WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userLevel: 0,
    banners: [],
    rows:[],
    uploading: false,
    maskHidden: false,
    imagePath: ''
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    this.getBanner();

    this.getList();
  },

  onShow: function () {
    this.setData({ userLevel: userInfoStore.userInfo.level })
    let giftBag = this.selectComponent("#giftbag");
    app.displayGiftBag(giftBag);
  },

  getBanner:function(){
    var self = this;
    api.getbanner({ pageNo: 2 }).then(res => {
      self.setData({
        banners: res.result
      })
    })
  },

  getList: function () {
    var self = this;
    api.getcouponlist().then(res => {
      // console.log(res);
      let { result } = res;
      
      self.setData({
        rows:result
      });
      wx.stopPullDownRefresh();
    }, err => { });

  },

  buyCoupon:function(e){
    let item = e.currentTarget.dataset.item;
    // console.log(item);

    if(item.couponId){
      let today = new Date();
      // let s = today.getFullYear() + '/' + (today.getMonth() + 1) + '/' + today.getDate() + ' ' + today.getHours() + ':' + today.getMinutes() + ':' + today.getSeconds();
      // console.log(today)
      // console.log(s)
      if (item.coupon.beginGrandTime) {
        let begin = new Date(item.coupon.beginGrandTime);
        if (today - begin < 0) {
            wx.showToast({
              icon: "none",
              title: "敬请期待!"
            })
            return;
        }
      }
      
      if (item.coupon.endGrandTime) {
        let end = new Date(item.coupon.endGrandTime);
        if (today-end>0){
          wx.showToast({
            icon: "none",
            title: "活动已结束,更多精彩敬请期待!"
          })
          return;
        }
      }
      if (item.coupon.couponType==1){
        this.addCoupon(item.couponId);
      } else {
        wx.navigateTo({
          url: 'detail?couponId=' + item.couponId,
        })
      }
    } else {
      if (item.clickUrl) {
        wx.navigateTo({
          url: item.clickUrl,
        })
      }
    }
  },

  getPhoneNumber: function (e) {
    // console.log(e);
    if (e.detail.iv) {
      let { session_key } = userInfoStore.userInfo;
      let pc = new WXBizDataCrypt(AppId, session_key);
      var ret = pc.decryptData(e.detail.encryptedData, e.detail.iv)
      console.log('解密后 data: ', ret)
      
      var param = {
        openId: userInfoStore.userInfo.openId,
        phone: ret.phoneNumber,
        level: 1
      }
      if (app.globalData.inviteCode)
        param = Object.assign(param, { recomendCode: app.globalData.inviteCode })
      var self = this
      
      api.saveUser(param).then(res => {
        let { userInfo } = userInfoStore;
        let { result } = res;
        result.session_key = userInfo.session_key;
        userInfoStore.updateUserInfo(result);
        wx.showModal({
          title: "提交成功",
          showCancel: false,
          confirmText: "我知道了",
          success: function (res) {
            if (res.confirm) {
              self.setData({
                userLevel: userInfoStore.userInfo.level
              });
            }
          }
        })
      }, err => {
        wx.showModal({
          title: "提交失败",
          content: err,
          showCancel: false,
          confirmText: "我知道了"
        })
      })

    }
  },

  addCoupon:function(cid){
    let param = {
      openId: userInfoStore.userInfo.openId,
      couponId: cid
    };
    api.useraddfreecoupon(param).then(res => {
      
      wx.showToast({
        icon: "none",
        title: "已将优惠券保存至您的卡包"
      })
    },err=>{
      wx.showToast({
        icon: "none",
        title: err
      })
    })
  },

  showdetail:function(e){
    // this.addCoupon(e.currentTarget.dataset.item.id);
    // let detailImage = e.currentTarget.dataset.item.detailImage;
    // if (detailImage){
    //   this.setData({
    //     imagePath: e.currentTarget.dataset.item.detailImage,
    //     maskHidden: true
    //   });
    // }
  },

  closeMask: function () {
    this.setData({
      maskHidden: !this.data.maskHidden
    });
  },

  savePosteToPhotosAlbum: function () {

    wx.downloadFile({
      url: this.data.imagePath, 
      success: function (res) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success(res) {
              wx.showToast({
                title: '已保存到相册~',
              })
            }
          });
      }
    })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getBanner();

    this.getList();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    getApp().share();
  }
})